package org.kfive.nova.thread;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/*
* QueueExample.java
* Created  by  lizhanwu
* Created on 2016-6-2 14:16
*/
public class QueueExample {

    public class Producer implements Runnable{

        private final BlockingQueue<String> queue;

        public Producer(BlockingQueue<String> queue){
            this.queue = queue;
        }

        public void run() {
            int i=0;
            while (true){
                String msg = "第"+i+"条消息";
                try {
                    System.out.println("producer make message:"+msg);
                    this.queue.put(msg);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                i++;
            }
        }
    }

    public class Consumer implements Runnable{

        private final BlockingQueue<String> queue;

        public Consumer(BlockingQueue<String> queue){
            this.queue = queue;
        }

        public void run() {
            String msg="";
            while (true) {
                try {
                    msg = this.queue.take();
                    System.out.println("consumer consume message:" + msg);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void test() {
        BlockingQueue<String> queue = new ArrayBlockingQueue<String>(10);
        new Thread(new Consumer(queue)).start();
        new Thread(new Consumer(queue)).start();
        new Thread(new Producer(queue)).start();
    }

    public static void main(String[] args) {
        QueueExample example = new QueueExample();
//        example.test();
        BlockingQueue<String> queue = new ArrayBlockingQueue<String>(10);
        new Thread(example.new Consumer(queue)).start();
        new Thread(example.new Consumer(queue)).start();
        new Thread(example.new Producer(queue)).start();

    }
}
